package com.zookeeper.basic.one;

import org.apache.log4j.pattern.CachedDateFormat;
import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created by 58 on 2016-7-15.
 * 使用异步的方式创建zk节点
 */
public class ZkCreateAsync  implements Watcher{
    //创建信号量
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    public void process(WatchedEvent event) {
        if(Event.KeeperState.SyncConnected == event.getState()){
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181",5000,new ZkCreateAsync());
        countDownLatch.await();
        zooKeeper.create("/zk-test-ephemeral-","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,new IStringCallBack(),"i am context....");
        zooKeeper.create("/zk-test-ephemeral-","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,new IStringCallBack(),"i am context....");
        zooKeeper.create("/zk-test-ephemeral-","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL,new IStringCallBack(),"i am context....");
        Thread.sleep(Integer.MAX_VALUE);
    }
}

class IStringCallBack  implements AsyncCallback.StringCallback{

    public void processResult(int rc, String path, Object ctx, String name) {
        System.out.println("create path result : [ "+rc+", "+path+", "+ctx+", real path name:"+name);

    }
}
